package speed.mybatis;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.logicalcobwebs.proxool.ProxoolDriver;

import speed.jdbc.datasource.DriverManagerDataSource;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.name.Named;

/**
 * @author zhaohaolin(zhaohaolin2010@gmail.com)
 */
public class ProxoolPooledDriverManagerDataSourceProvider implements
		Provider<DataSource> {

	@Inject
	public ProxoolPooledDriverManagerDataSourceProvider(
			@Named("proxool.alias") final String alias) {
		dataSource = new DriverManagerDataSource(alias);
		dataSource.setDriverClassName(ProxoolDriver.class.getName());
		try {
			// 先测试连接一次
			Connection conn = dataSource.getConnection();
			if (!conn.isClosed()) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	@Inject(optional = true)
	public void setLoginTimeout(
			@Named("JDBC.loginTimeout") final int loginTimeout) {
		try {
			dataSource.setLoginTimeout(loginTimeout);
		} catch (SQLException e) {
			throw new RuntimeException((new StringBuilder())
					.append("Impossible to set login timeout '")
					.append(loginTimeout).append("' to Unpooled Data Source")
					.toString(), e);
		}
	}

	public DataSource get() {
		return this.dataSource;
	}

	private final DriverManagerDataSource dataSource;

}
